<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">商户管理</h1>
      <a-button type="primary" @click="showCreateModal = true">
        <template #icon><plus-outlined /></template>
        新建商户
      </a-button>
    </div>
    <!-- 搜索栏 -->
    <a-card class="mb-6">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="商户名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入商户名称" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">未激活</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon><search-outlined /></template>
            搜索
          </a-button>
          <a-button class="ml-2" @click="handleReset">
            <template #icon><reload-outlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <!-- 商户列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'category'">
            <a-tag :color="record.category === 0 ? 'blue' : 'orange'">
              {{ record.category === 0 ? '普通商户' : '特约商户' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'success' : 'default'">
              {{ record.status === 'active' ? '活跃' : '未激活' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除这个商户吗？" @confirm="handleDelete(record)">
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 新建商户弹窗 -->
    <a-modal v-model:open="showCreateModal" title="创建商户" @ok="handleCreate" :confirmLoading="createLoading">
      <a-form :model="createForm" layout="vertical">
        <a-form-item label="商户名称" name="name" :rules="[{ required: true, message: '请输入商户名称' }]">
          <a-input v-model:value="createForm.name" placeholder="请输入商户名称" />
        </a-form-item>
        <a-form-item label="商户类别" name="category" :rules="[{ required: true, message: '请选择商户类别' }]">
          <a-select v-model:value="createForm.category">
            <a-select-option :value="0">普通商户</a-select-option>
            <a-select-option :value="1">特约商户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="createForm.category === 1" label="所属代理商" name="agent">
          <a-input v-model:value="createForm.agent" placeholder="请输入所属代理商" />
        </a-form-item>
        <a-form-item v-if="createForm.category === 1" label="服务商" name="provider">
          <a-input v-model:value="createForm.provider" placeholder="请输入服务商" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="createForm.remark" placeholder="请输入备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 编辑商户弹窗 -->
    <a-modal v-model:open="showEditModal" title="编辑商户" @ok="handleUpdate" :confirmLoading="editLoading">
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="商户名称" name="name" :rules="[{ required: true, message: '请输入商户名称' }]">
          <a-input v-model:value="editForm.name" placeholder="请输入商户名称" />
        </a-form-item>
        <a-form-item label="商户类别" name="category" :rules="[{ required: true, message: '请选择商户类别' }]">
          <a-select v-model:value="editForm.category">
            <a-select-option :value="0">普通商户</a-select-option>
            <a-select-option :value="1">特约商户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="editForm.category === 1" label="所属代理商" name="agent">
          <a-input v-model:value="editForm.agent" placeholder="请输入所属代理商" />
        </a-form-item>
        <a-form-item v-if="editForm.category === 1" label="服务商" name="provider">
          <a-input v-model:value="editForm.provider" placeholder="请输入服务商" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="editForm.remark" placeholder="请输入备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { mockData, addMerchant, updateMerchant, deleteMerchant, type MerchantItem } from './data'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'

const searchForm = reactive({
  name: '',
  status: '',
})
const columns = [
  { title: '商户ID', dataIndex: 'id', key: 'id' },
  { title: '商户名称', dataIndex: 'name', key: 'name' },
  { title: '商户类别', dataIndex: 'category', key: 'category' },
  { title: '所属代理商', dataIndex: 'agent', key: 'agent' },
  { title: '服务商', dataIndex: 'provider', key: 'provider' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '备注', dataIndex: 'remark', key: 'remark' },
  { title: '操作', key: 'action', width: 180 },
]
const loading = ref(false)
const tableData = ref<MerchantItem[]>(mockData)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: mockData.length,
})
const showCreateModal = ref(false)
const createLoading = ref(false)
const createForm = reactive({
  name: '',
  category: 0 as 0 | 1,
  agent: '',
  provider: '',
  remark: '',
})
const showEditModal = ref(false)
const editLoading = ref(false)
const editForm = reactive({
  id: '',
  name: '',
  category: 0 as 0 | 1,
  agent: '',
  provider: '',
  remark: '',
})
const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    const filtered = mockData.filter(item => {
      const nameMatch = !searchForm.name || item.name.includes(searchForm.name)
      const statusMatch = !searchForm.status || item.status === searchForm.status
      return nameMatch && statusMatch
    })
    tableData.value = filtered
    pagination.total = filtered.length
    loading.value = false
  }, 500)
}
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}
const handleCreate = () => {
  const baseDate = '20250601'
  const randomNum = String(Math.floor(Math.random() * 90000) + 10000)
  const id = `M${baseDate}${randomNum}`
  // 普通商户 agent/provider 置空
  const agent = createForm.category === 1 ? createForm.agent : ''
  const provider = createForm.category === 1 ? createForm.provider : ''
  const newMerchant: MerchantItem = {
    id,
    name: createForm.name,
    category: createForm.category,
    agent,
    provider,
    status: 'active',
    createTime: new Date().toLocaleString(),
    remark: createForm.remark,
  }
  addMerchant(newMerchant)
  tableData.value = [...mockData]
  message.success('创建成功')
  showCreateModal.value = false
  createForm.name = ''
  createForm.category = 0 as 0 | 1
  createForm.agent = ''
  createForm.provider = ''
  createForm.remark = ''
}
const handleEdit = (record: MerchantItem) => {
  editForm.id = record.id
  editForm.name = record.name
  editForm.category = record.category
  editForm.agent = record.agent || ''
  editForm.provider = record.provider || ''
  editForm.remark = record.remark || ''
  showEditModal.value = true
}
const handleUpdate = () => {
  // 普通商户 agent/provider 置空
  const agent = editForm.category === 1 ? editForm.agent : ''
  const provider = editForm.category === 1 ? editForm.provider : ''
  updateMerchant(editForm.id, { name: editForm.name, category: editForm.category, agent, provider, remark: editForm.remark })
  const idx = tableData.value.findIndex(item => item.id === editForm.id)
  if (idx > -1) {
    tableData.value[idx].name = editForm.name
    tableData.value[idx].category = editForm.category
    tableData.value[idx].agent = agent
    tableData.value[idx].provider = provider
    tableData.value[idx].remark = editForm.remark
  }
  tableData.value = [...mockData]
  message.success('更新成功')
  showEditModal.value = false
}
const handleDelete = (record: MerchantItem) => {
  deleteMerchant(record.id)
  const idx = tableData.value.findIndex(item => item.id === record.id)
  if (idx > -1) tableData.value.splice(idx, 1)
  tableData.value = [...mockData]
  message.success('删除成功')
}
</script>

<style scoped>
.ant-card {
  border-radius: 8px;
}
.ant-table-wrapper {
  border-radius: 8px;
  overflow: hidden;
}
.ant-tag {
  border-radius: 4px;
}
</style>